import os
import re
import sys
import PIL
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from itertools import chain
from fontTools.ttLib import TTFont, woff2
from fontTools.unicode import Unicode


def load_font(path):
    ttf = TTFont(path)
    # 获得cmap中的信息
    chars = chain.from_iterable(
        [y + (Unicode[y[0]], )
        for y in x.cmap.items()] for x in ttf['cmap'].tables)
    chars = set(chars)
    chars = sorted(chars, key=lambda c: int(c[0]))

    ttf.close()
    return chars


def convert_ttf(path, fontsize=60, w=96, h=96):
    base = os.path.basename(path)
    dirs = os.path.splitext(base)[0]
    if not os.path.exists(dirs):
        os.mkdir(dirs)
    chars = load_font(path)
    # 定义字体对象
    font = ImageFont.truetype(path, fontsize)
    for c in chars:
        if re.match('.notdef|nonmarkingreturn|.null', c[1]):
            continue
        # 创建画板
        img = Image.new('RGB', (w, h), (255, 255, 255))
        draw = ImageDraw.Draw(img)
        # 获得字体大小
        (ws, hs) = font.getsize(chr(c[0]))
        # （画板w - 字体ws) / 2 = 让字体在画面中居中
        wb = (w - ws) * 0.5
        hb = (h - hs) * 0.5
        # 绘制文字
        draw.text((wb, hb), chr(c[0]), (0, 0, 0), font=font)
        draw = ImageDraw.Draw(img)
        # img.save('{}/{:d}.png'.format(dirs, c[1]))
        img.save(os.path.join(dirs, c[1]) + '.png')


def test():
    """支持 ttf 格式和 woff 格式"""
    convert_ttf('iconfont.ttf')
    convert_ttf('myword.woff')

test()



